package com.oa.modules.approvalsec1.controller;

import com.oa.common.utils.*;
import com.oa.modules.approvalsec1.entity.DataDocumentEntity;
import com.oa.modules.approvalsec1.service.DataDocumentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.Map;


/**
 * 图片视频上传
 *
 * @author jiangwei
 * @date 2020-09-18 16:43:52
 */

@RestController
@Api(tags = "图片视频上传")
@RequestMapping("file")
public class ImageController {
    private static String realPath;

    @Autowired
    private DataDocumentService dataDocumentService;

    /**
     * 通用上传文件、图片接口
     *
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/uploadFile")
    @ApiOperation(value = "文件上传")
    public R uploadFile(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IllegalStateException, IOException {
        //进行分布式对象存储Ambry文件上传·
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        request.setCharacterEncoding("utf-8");
        MultipartFile file = req.getFile("file");
        if (file != null) {
            String fileName = file.getOriginalFilename();// 文件原名称
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (prefix.equals("mp4")) {
                String accessToken = SenInfoCheckUtil.getAccessToken();
                //保存文件  
                String imageUrl = FileUtil.ImageUpload(file, request);
                File newFile = new File(imageUrl);
                if (!newFile.isFile()) {
                    return R.error(1, imageUrl);
                }
//                    String imageHtmlUrl = imageUrl.replaceAll("/home/image","https://www.qhspj.com/").replaceAll("/home/file","https://www.qhspj.com/");
                String imageHtmlUrl = imageUrl.replaceAll("/home/image", "https://www.qhspj.com/").replaceAll("/home/file", "https://www.qhspj.com/");
                String fileCover = "";
                try {        //截图视频的第一帧
                    String trueFileName = System.currentTimeMillis() + fileName.replace("mp4", "jpg"); //15312196403485.jpg
                    String realUrl = realPath + "image/" + AppUtils.getUUID();
                    File d = new File(realUrl);
                    d.mkdirs();
                    fileCover = realUrl + "/" + trueFileName;
                    videoSplit.getTempPath(fileCover, imageUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                    fileCover = fileCover.replaceAll("/home/image","https://www.qhspj.com/");
                fileCover = fileCover.replaceAll("/home/image", "https://www.qhspj.com/");
                return R.ok().put("url", imageUrl).put("HtmlUrl", imageHtmlUrl).put("fileCover", fileCover);
            } else {
                String accessToken = SenInfoCheckUtil.getAccessToken();
                String imageUrl = FileUtil.ImageUpload(file, request);
                File newFile = new File(imageUrl);
                if (!newFile.isFile()) {
                    return R.error(1, imageUrl);
                }
                String imageHtmlUrl = imageUrl.replaceAll("/home/image", "https://www.qhspj.com/").replaceAll("/home/file", "https://www.qhspj.com/");
//                    String imageHtmlUrl = imageUrl.replaceAll("/home/image","https://www.qhspj.com/").replaceAll("/home/file","https://www.qhspj.com/");
                return R.ok().put("url", imageUrl).put("HtmlUrl", imageHtmlUrl);
            }
        }
        return R.error(1, "文件为空");
    }


    /**
     * 齐河大数据共享平台通用上传文件、图片接口
     *
     * @param request
     * @param response
     * @param session
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/uploadFileByQh")
    @ApiOperation(value = "文件上传")
    public R uploadFileByQh(@RequestParam Map<String, String> param, HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IllegalStateException, IOException, IOException {
        //进行分布式对象存储Ambry文件上传
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        request.setCharacterEncoding("utf-8");
        MultipartFile file = req.getFile("file");
        if (file != null) {
            // 文件原名称
            String fileName = file.getOriginalFilename();
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (prefix.equals("gif") || prefix.equals("bmp") || prefix.equals("jpg") || prefix.equals("tif") || prefix.equals("jpeg") || prefix.equals("png")) {
                //保存文件  
                String imageUrl = FileUtil.ImageUpload(file, request);
                File newFile = new File(imageUrl);
                if (!newFile.isFile()) {
                    return R.error(1, imageUrl);
                }
                String imageHtmlUrl = imageUrl.replaceAll("/home/image", "https://www.qhspj.com").replaceAll("/home/file", "https://www.qhspj.com");
                //如果这个公司在这个事项的这个类别中没有存有文件。新建
                DataDocumentEntity dataDocument = new DataDocumentEntity();
                dataDocument.setId(AppUtils.getUUID());
                dataDocument.setCreateDate(new Date());
                dataDocument.setCreateOper("1");
                dataDocument.setCompanyName(param.get("company"));
                dataDocument.setMatterName(param.get("matter"));
                dataDocument.setFileName(param.get("fileName"));
                dataDocument.setTopCategory(param.get("topCategory"));
                dataDocument.setLowerCategory(param.get("lowerCategory"));
                dataDocument.setUploadingDate(param.get("uploadingDate"));
                dataDocument.setCeitificateDate(param.get("ceitificateDate"));
                dataDocument.setLicenseId(param.get("licenseId"));
                dataDocument.setFileUrl(imageHtmlUrl);
                dataDocumentService.save(dataDocument);
                return R.ok().put("url", imageUrl).put("HtmlUrl", imageHtmlUrl);
            } else {
                String imageUrl = FileUtil.ImageUpload(file, request);
                File newFile = new File(imageUrl);
                if (!newFile.isFile()) {
                    return R.error(1, imageUrl);
                }
                String imageHtmlUrl = imageUrl.replaceAll("/home/image", "https://www.qhspj.com").replaceAll("/home/file", "https://www.qhspj.com");
                //如果这个公司在这个事项的这个类别中没有存有文件。新建
                DataDocumentEntity dataDocument = new DataDocumentEntity();
                dataDocument.setId(AppUtils.getUUID());
                dataDocument.setCreateDate(new Date());
                dataDocument.setCreateOper("1");
                dataDocument.setCompanyName(param.get("company"));
                dataDocument.setMatterName(param.get("matter"));
                dataDocument.setFileName(param.get("fileName"));
                dataDocument.setTopCategory(param.get("topCategory"));
                dataDocument.setLowerCategory(param.get("lowerCategory"));
                dataDocument.setUploadingDate(param.get("uploadingDate"));
                dataDocument.setCeitificateDate(param.get("ceitificateDate"));
                dataDocument.setLicenseId(param.get("licenseId"));
                dataDocument.setFileUrl(imageHtmlUrl);
                dataDocumentService.save(dataDocument);
                return R.ok().put("url", imageUrl).put("HtmlUrl", imageHtmlUrl);
            }
        }
        return R.error(1, "文件为空");
    }

    /**
     * 文件删除
     *
     * @throws IllegalStateException
     * @throws IOException
     */
    @ResponseBody
    @PostMapping("/deleteFile")
    @ApiOperation(value = "文件删除")
    public R deleteFile(String url) throws IllegalStateException, IOException {
        FileUtil.delFolder(url);
        return R.ok();
    }

    public static String getRealPath() {
        return realPath;
    }

    @Value("${url.saveUrl}")
    public void setRealPath(String realPath) {
        ImageController.realPath = realPath;
    }

    public static String getFilePath() {
        return realPath;
    }
}
